<template>
	<view v-if="dataList.length>0" class="file-block">
		<u-divider>{{title}}</u-divider>
		<view class="file-list" :index="index" v-for="(item, index) in dataList" :key="index">
			<view class="file-item" @click="previewPDF(item.url)">
				<image src="/static/icon-pdfs.png" style="width: 42rpx; height: 42rpx; margin-right: 10rpx;"></image>
				<text>{{item.attachmentName}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/common/js/config.js';
	const apiUrl = "/api/Jiushi/Customerattachment";
	export default {
		props: {
			customerId: {
				type: [Number, String],
				default () {
					return ''
				}
			},
			businessId: {
				type: [Number, String],
				default () {
					return ''
				}
			},
			title: {
				type: String,
				default () {
					return ''
				}
			},
			type: {
				type: String,
				default () {
					return ''
				}
			}
		},
		data() {
			return {
				dataList: []
			};
		},
		watch: {
			businessId: {
				immediate: true,
				deep: true,
				handler(val) {
					this.getListData()
				}
			}
		},
		methods: {
			previewPDF(pdfUrl) {
				if (!pdfUrl) {
					uni.showToast({
						title: 'PDF文件链接不存在',
						icon: 'none'
					});
					return;
				}
				uni.downloadFile({
					url: pdfUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								fileType: 'pdf',
								success: () => {
									console.log('PDF预览成功');
								},
								fail: (err) => {
									console.error('PDF预览失败', err);
									uni.showToast({
										title: 'PDF预览失败',
										icon: 'none'
									});
								}
							});
						} else {
							uni.showToast({
								title: '文件下载失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('文件下载失败', err);
						uni.showToast({
							title: '文件下载失败',
							icon: 'none'
						});
					}
				});
			},
			getListData() {
				this.$helper.ajax({
					url: `${apiUrl}?customerId=${this.customerId}&attachmentType=${this.type}`,
					method: "GET",
					contentType: "application/json",
					success: res => {
						if (res.data.data) {
							this.dataList = res.data.data.list.map(item => {
								if (item.attachmentPath.indexOf("https") > -1) {
									item.url = item.attachmentPath
								} else {
									item.url = config.Global.baseUrl.api.apiUrl + item.attachmentPath
								}
								return item
							})
						}
					}
				});
			}
		},
	}
</script>
<style lang="scss" scoped>
	.file-block {
		padding: 0 24rpx 24rpx;
		background: #fff;

		.file-title {
			width: 100%;
			font-size: 28rpx;
			text-align: left;
			font-weight: 500;
			line-height: 60rpx;
		}

		.file-list {
			display: flex;
			flex-direction: column;

			.file-item {
				display: flex;
				align-items: center;
				margin-top: 20rpx;

				text {
					flex: 1;
					text-overflow: ellipsis;
					overflow: hidden;
				}
			}
		}
	}
</style>